
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:keep_account/bean/work_records.dart';
import 'package:keep_account/dio/DefaultRequestResult.dart';
import 'package:keep_account/dio/http_request.dart';
import 'package:keep_account/vm/base_controller.dart';

class WorkRecordsController extends BaseController {

  var totalSalary = .0.obs;
  var totalDays = 0.obs;

  var workRecords = <WorkRecords>[].obs;
  var productQuantityController = TextEditingController();
  var productPriceController = TextEditingController();
  var teamSizeController = TextEditingController();

  @override
  void onReady() {
    super.onReady();
    getCurrentMonthRecords();
  }

  @override
  void retry() {
    getCurrentMonthRecords();
  }
  void getCurrentMonthRecords(){
    HttpRequest().getCurrentMonthWorkRecords(
        requestResult: DefaultRequestResult(
            success: (data){
              totalSalary.value = .0;
              var result = (data as List<dynamic>).map((e) => WorkRecords.fromJson(e as Map<String,dynamic>)).toList();
              var salaryMap = <int,double>{};
              for (var element in result) {
                var last = salaryMap[element.teamSize] ?? 0;
                salaryMap[element.teamSize ?? 0] = last + ((element.productPrice ?? 0) * (element.productQuantity ?? 0));
              }
              print(salaryMap);
              for (var element in salaryMap.keys) {
                totalSalary.value += ((salaryMap[element] ?? 0) / element);
              }
              totalDays.value = result.length;
              workRecords.clear();
              workRecords.addAll(result);
              change(null,status: RxStatus.success());
            },
            emptyData: (){
              change(null,status: RxStatus.empty());
            },
            error: (error){
              EasyLoading.showError(error.message);
              change(null,status: RxStatus.error(error.message));
            }
        ));
  }

  void updateWorkRecords(WorkRecords data){
    HttpRequest().updateWorkRecords(
    data.copyWith(
        productQuantity: int.tryParse(productQuantityController.value.text),
        productPrice: double.tryParse(productPriceController.value.text),
        teamSize: int.tryParse(teamSizeController.value.text)
    ),
    requestResult: BoolRequestResult(
        success: (){
          EasyLoading.showSuccess("更新成功");
          getCurrentMonthRecords();
        }, 
        error: (error){
          EasyLoading.showError(error.message);
        }
    ));
  }

  void deleteWorkRecords(int id){
    HttpRequest().deleteWorkRecordsById(
        id,
        requestResult: BoolRequestResult(
            success: (){
              EasyLoading.showSuccess("删除成功");
              retry();
            },
            error: (error){
              EasyLoading.showError(error.message);
            }
        ));
  }

}